<template>
  <div class="app-container">
    <!-- 查询 -->
    <!-- <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" v-if="isHeaderDisplay">
      <template slot="search">
        <el-form-item label="策划书名称">
          <el-input v-model="queryParam.qry_proposalname" placeholder="名称关键字" @keyup.enter.native="doQuery">
          </el-input>
        </el-form-item>
        <el-form-item label="策划书编号">
          <el-input v-model="queryParam.qry_proposalcode" placeholder="策划书编号" @keyup.enter.native="doQuery">
          </el-input>
        </el-form-item>
      </template>
    </tl-list-search> -->
    <!-- 工具栏 -->
    <tl-list-toolbar class="tl-list-toolbar" style="margin:6px 0 10px 0" ref="toolbar" :refMainTable="$refs.mainTable" currentModuleTableCode="sdProjectPlan/main" :startColumn="3" @add="openAddDialog('editForm')" :isDisplayExport="false" @exportExcel="doExportExcel" @deleteBatch="doDeleteBatch" @refresh="doRefresh" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :isDisplayAdd="$store.getters.roles[0] === 'pm'"  :isDisplayDeleteBatch="false">
      <template slot="left-btn"> </template>
    </tl-list-toolbar>
    <div>
      <!-- 列表选择 -->
      <div class="table-alert-div" ref="selector">
        <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
          <template slot="title">
            已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRowKeys.length }}</a
            >项&nbsp;&nbsp;
            <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
          </template>
        </el-alert>
      </div>
      <!--表格渲染-->
      <el-table class="tl-table" ref="mainTable" :height="tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
        <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
        <el-table-column label="待处理" width="80px" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-tag v-if="isInApprovalList(scope.row)" type="success">是</el-tag>
            <template v-else
              >否</template
            >
          </template>
        </el-table-column>
        <el-table-column prop="proposalname" label="策划书名称" min-width="350px" sortable="custom" sort-by="proposalname" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="proposalcode" label="策划书编号" width="130px" sortable="custom" sort-by="proposalcode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="plandescription" label="策划书描述" min-width sortable="custom" sort-by="plandescription" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column prop="version" label="版本" width="80px" sortable="custom" sort-by="version" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <span>v{{scope.row.version}}.0</span>
          </template>
        </el-table-column>
        <el-table-column prop="submitdate" label="提交时间" width="100px" sortable="custom" sort-by="submitdate" align="center" header-align="center" :formatter="dateTimeFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispstate" label="状态" width="100px" sortable="custom" sort-by="state" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-tag :type="changeStateType(scope.row.state)">
              {{ scope.row.dispstate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="latestphase" label="最新阶段" width="150px" sortable="custom" sort-by="latestphase" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="100px" v-slot="scope" fixed="right">
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-edit" @click.native="openEditDialog('editForm', scope.row.id)" :disabled="scope.row.state !== 0 && scope.row.state !== 2">编辑</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" :disabled="scope.row.state !== 0 && scope.row.state !== 2" @click.native="doDelete(scope.row.id)">删除</el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" @click.native="checkIsApproval(scope.row.id)">查看 </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </el-table>
      <!-- 列表分页 -->
      <el-row class="pagebar" ref="pager">
        <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
      </el-row>
      <tl-edit ref="editForm" @refresh="doRefresh" :projectinfo="projectinfo" :oldmilepost="oldmilepost" :planstate="planstate"></tl-edit>
      <tl-approval-edit ref="approvalEditForm" @refresh="doRefresh"></tl-approval-edit>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import tlEdit from './edit'
import tlApprovalEdit from '@/views/cbo/cboApprovalNodeIns/approvalOne'
import { checkPermission } from '@tapui/utils/permission'
/** 工具类 */
import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
export default {
  name: 'sdProjectPlan',
  mixins: [mixin_list],
  components: { tlEdit, tlApprovalEdit },
  data() {
    return {
      description: '项目策划-列表查询',
      urlPrefix: '/sd/projectPlan/',
      url: {
        queryCodeList: '/sd/projectPlan/dataCodeList',
        checkIsApproval: '/sd/projectPlan/checkIsApproval',
        queryApprovalList: '/cbo/approvalNodeIns/queryApprovalList',
        ifReviewed: '/sd/projectReview/ifReviewed'
      },
      reduceHeight: 292,
      // 排序参数
      sorterInfo: {
        sidx: 'createon',
        sord: 'desc'
      },
      oldmilepost: [],
      planstate: '',
      nodeinsid: '',
      // 审批列表
      approvalDataList: [],
      sourcetype: 'GpmProjectPlan'
    }
  },
  props: {
    projectinfo: {}
  },
  computed: {
    isPM() {
      if (this.$store.getters.projectroles) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 审批结束后刷新列表和顶部tab
    doRefresh() {
      this.loadData({})
      this.$emit('refreshIndex')
    },
    checkIsApproval(id) {
      let param = {
        sourceid: id,
        sourcetype: 'SdProjectPlan'
      }
      getAction(this.url.checkIsApproval, param).then((res) => {
        if (res.success) {
          if (res.result.isapprover) {
            this.$refs.approvalEditForm.nodeInsId = res.result.nodeinsid
            this.openViewDialog('approvalEditForm', id)
          } else {
            this.openViewDialog('editForm', id)
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 打开详情对话框实现*/
    openViewDialog(editForm, id) {
      getAction('/sd/projectPlan/load?', { id: id }).then((res) => {
        if (res.success) {
          this.planstate = res.result.state
          if (!this.beforeOpenViewDialog(editForm, id)) {
            return
          }
          this.$refs[editForm].id = id
          this.$refs[editForm].isAdd = false
          this.$refs[editForm].visible = true
          this.$refs[editForm].disableEditSubmit = true
          this.$nextTick(() => {
            this.afterOpenViewDialog(editForm, id)
          })
          let that = this
          setTimeout(() => {
            that.clickRowkey = id
          }, 100)
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    beforeLoadData() {
      if (!this.projectinfo) {
        return false
      }
      this.queryParam.qry_projectcode = this.projectinfo.projectcode
      this.getApprovalDataList()
      return true
    },
    /** 打开新增对话框实现，添加复盘校验 */
    openAddDialog(editForm, rowData) {
      getAction(this.url.ifReviewed, { projectid: this.projectinfo.id }).then((res) => {
        if (res.success) {
          if (res.result) {
            this.$tap.alert('该项目已提交复盘审批，无法新增单据!')
          } else {
            if (!this.beforeOpenAddDialog(editForm, rowData)) {
              return
            }
            this.$refs[editForm].isAdd = true
            this.$refs[editForm].visible = true
            this.$refs[editForm].disableEditSubmit = false
            this.$nextTick(() => {
              this.afterOpenAddDialog(editForm, rowData)
            })
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
      .catch((err) => {
          this.$tap.alert(err, 'warninig')
      })
    },
    beforeOpenAddDialog() {
      let isHaveApprovalingDatas = false
      this.datas.forEach((element) => {
        if (element.state === 1 || element.state === 0 || element.state === 2) {
          isHaveApprovalingDatas = true
        }
      })
      if (isHaveApprovalingDatas) {
        this.$tap.confirm('存在开立或者审批中的单据，无法新增单据').then((_) => {
          return false
        })
      } else {
        return true
      }
    },
    afterLoadData() {
      let planid = ''
      // this.datas.forEach(element => {
      //     if (element.state === 9 && element.enabled === 1) {
      //         planid = element.id
      //     }
      // })
      for (let i = 0; i < this.datas.length; i++) {
        if (this.datas[i].state === 9 && this.datas[i].enabled === 1) {
          planid = this.datas[i].id
          break
        }
      }
      if (planid !== '') {
        var params = {
          qry_planid: planid
        }
        getAction('sd/projectMilepost/list', params).then((res) => {
          if (res.success) {
            this.oldmilepost = res.result.dataList
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    /** 表格双击事件 */
    doRowDbClick(row, column, event) {
      // 判断双击打开是查看还是编辑
      if (row.state === 0 || row.state === 2) {
        this.rowDbClickActionType = 'edit'
      } else {
        this.rowDbClickActionType = 'view'
      }
      if (this.rowDbClickActionType === 'edit') {
        // 判断是否有权限
        if (this.editPermission.length > 0) {
          if (checkPermission(this.editPermission)) {
            this.openEditDialog('editForm', row[this.$refs.mainTable.rowKey])
          } else {
            this.openViewDialog('editForm', row[this.$refs.mainTable.rowKey])
          }
        } else {
          this.openEditDialog('editForm', row[this.$refs.mainTable.rowKey])
        }
      } else if (this.rowDbClickActionType === 'view') {
        this.checkIsApproval(row[this.$refs.mainTable.rowKey])
        // this.openViewDialog('editForm', row[this.$refs.mainTable.rowKey])
      }
    },
    created() {
      this.LoadData()
      // this.datas.forEach(element => {
      //   if (element.state === 9 && element.enabled === 1) {
      //     // this.newplanid = element.id
      //     var params = {
      //       qry_planid: element.id
      //     }
      //     getAction('sd/projectMilepost/list', params).then(res => {
      //       if (res.success) {
      //         this.oldmilepost = res.result.dataList
      //       } else {
      //         this.$tap.alert(res.message, "warning")
      //       }
      //     })
      //   }
      // })
    },
    // 禁用表格前面的选择
    doDisableCheckBox(row, index) {
      if (row.state !== 0 && row.state !== 2) {
        return false
      } else {
        return true
      }
    },
    // 获取用户当前待审批列表 =>approvalDataList
    getApprovalDataList() {
      // 参数 在com.topscomm.sd.cboController.CboApprovalNodeInsController#queryApprovalList 里面
      let approvalParam = {
        qry_sourcetype: this.sourcetype,
        qry_approvaluserid: this.user.id,
        sidx: 'nodeins.createon',
        currentPage: '1',
        pageSize: '1000'
      }

      getAction(this.url.queryApprovalList, approvalParam)
        .then((res) => {
          if (res.success) {
            this.approvalDataList = res.result.dataList
          }
        })
        .catch((err) => {
          this.$tap.alert(err, 'warninig')
        })
    },
    isInApprovalList(row) {
      return this.approvalDataList.filter((item) => item.sourceid === row.id).length > 0
    },
    /** 改变审核状态标签颜色 */
    changeStateType(state) {
      return state === 0 ? 'info' : state === 2 ? 'danger' : state === 9 ? 'success' : ''
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  margin: 0;
}
</style>
